<?php

class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $identity = Zend_Auth::getInstance()->getIdentity();

        $messagesTable = new Application_Model_DbTable_Messages();

        $select = $messagesTable->select()->order('id DESC');
        $paginator = Zend_Paginator::factory($select);
        $paginator->setCurrentPageNumber($this->getRequest()->getParam('page'));
        $this->view->paginator = $paginator;

        $messageForm = new Application_Form_Message();
        $messageForm->getElement('username')->setValue($identity->getUsername());

        if ($this->getRequest()->isPost()
            && $messageForm->isValid($this->getRequest()->getPost())
        ) {
            $newMessage = $messagesTable->fetchNew();
            $newMessage->setFromArray($messageForm->getValues());
            $newMessage->created_at = time();
            $newMessage->setCreatedBy($identity);
            $newMessage->save();
            $this->_redirect($this->getHelper('url')->url(array(), 'index'));
        }
        $this->view->messageForm = $messageForm;
    }
}
